﻿@{
    ViewBag.Title = "Danh sách nhân viên";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">

    var required = '<span style="color:red;font-weight:bold" data-qtip="Bắt buộc nhập">*</span>';

    Ext.Loader.setPath('Ext.ux', 'extjs/ux');

    Ext.require([
        'Ext.data.*',
        'Ext.grid.*',
        'Ext.ux.DataTip'
    ]);
    
    Ext.define('VTV.TaDMS.Extjs.Model.Employee', {
        extend: 'Ext.data.Model',
        fields: [{
            name: 'EmployeeId', mapping: 'EmployeeId', type: 'int'
        }, {
            name: 'DepartmentId', mapping: 'DepartmentId', type: 'int'
        }, {
            name: 'FirstName', mapping: 'FirstName', type: 'string'
        }, {
            name: 'LastName', mapping: 'LastName', type: 'string'
        }, {
            name: 'BirthDate', mapping: 'BirthDate', type: 'date'
        }, {
            name: 'Address', mapping: 'Address', type: 'string'
        }, {
            name: 'MobilePhone', mapping: 'MobilePhone', type: 'string'
        }, {
            name: 'Email', mapping: 'Email', type: 'string'
        }, {
            name: 'Note', mapping: 'Note', type: 'string'
        }],
        idProperty: 'EmployeeId'
    });

    Ext.onReady(function () {
        Ext.QuickTips.init();

        var employeeStore = Ext.create('Ext.data.Store', {
            model: 'VTV.TaDMS.Extjs.Model.Employee',
            autoLoad: { param: { start: 0, limit: 15 } },
            pageSize: 15,
            //autoSync: true,
            proxy: {
                type: 'ajax',
                api: {
                    create: '/api/ApiEmployee/Create',
                    read: '/api/ApiEmployee/GetAll',
                    update: '/api/ApiEmployee/Update',
                    destroy: '/api/ApiEmployee/Delete'
                },
                reader: {
                    root: 'data',
                    type: 'json',
                    successProperty: 'success',
                    messageProperty: 'message',
                    totalProperty: 'total'
                },
                writer: {
                    type: 'json',
                    writeAllFields: false
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        Ext.MessageBox.show({
                            title: 'Lỗi',
                            msg: operation.getError(),
                            icon: Ext.MessageBox.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
            },
            listeners: {
                write: function (store, operation) {
                    var record = operation.getRecords()[0],
                        name = Ext.String.capitalize(operation.action),
                        verb;


                    if (name == 'Destroy') {
                        record = operation.records[0];
                        verb = 'Destroyed';
                    } else {
                        verb = name + 'd';
                    }
                }
            }
        });

        var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
            listeners: {
                cancelEdit: function (editor, context) {
                    // Canceling editing of a locally added, unsaved record: remove it
                    if (context.record.phantom) {
                        store.remove(context.record);
                    }
                },
                edit: function (editor, context, eOpts) {
                    var result = '';
                    for (var i = 0; i < context.grid.columns.length; i++) {
                        if (context.record.isModified(context.grid.columns[i].dataIndex)) {
                            result = result + '$' + context.grid.columns[i].dataIndex;
                        }
                    }
                    
                    if (result.length > 0) {
                        
                        var entity = {
                            EmployeeId: context.record.get('EmployeeId'),
                            FirstName: context.record.get('FirstName'),
                            LastName: context.record.get('LastName'),
                            BirthDate: context.record.get('BirthDate'),
                            Address: context.record.get('Address').trim() != "" ? context.record.get('Address').trim() : null,
                            MobilePhone: context.record.get('MobilePhone'.trim()) != "" ? context.record.get('MobilePhone').trim() : null,
                            Email: context.record.get('Email').trim() != "" ? context.record.get('Email').trim() : null,
                            Note: context.record.get('Note').trim() != "" ? context.record.get('Note').trim() : null
                        };

                        Ext.Ajax.request({
                            url: '/api/ApiEmployee/Update',
                            method: 'POST',
                            jsonData: entity,
                            params: {
                                fields: result.substring(1)
                            },
                            success: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                if (responseData.success == true) {
                                    context.record.commit();
                                } else {
                                    alert("Lỗi. " + responseData.message);
                                }
                            },
                            failure: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                alert("Lỗi. " + responseData.message);
                            }
                        });
                        
                    }
                }
            }
        });

        var employeeGrid = Ext.create('Ext.grid.Panel', {
            store: employeeStore,
            plugins: [rowEditing],
            columns: [{
                text: 'Họ',
                width: 100,
                dataIndex: 'FirstName',
                field: { xtype: 'textfield' }
            }, {
                text: 'Tên',
                width: 70,
                dataIndex: 'LastName',
                field: { xtype: 'textfield' }
            }, {
                text: 'Ngày sinh',
                width: 110,
                dataIndex: 'BirthDate',
                renderer: Ext.util.Format.dateRenderer('d-m-Y'),
                field: { xtype: 'datefield' }
            }, {
                text: 'Điện thoại',
                width: 110,
                dataIndex: 'MobilePhone',
                field: { xtype: 'textfield' }
            }, {
                text: 'Email',
                width: 170,
                dataIndex: 'Email',
                field: { xtype: 'textfield' }
            }, {
                text: 'Địa chỉ',
                flex: 1,
                dataIndex: 'Address',
                field: { xtype: 'textfield' }
            }, {
                text: 'Ghi chú',
                flex: 1,
                dataIndex: 'Note',
                field: { xtype: 'textfield' }
            }, {
                menuDisabled: true,
                sortable: false,
                xtype: 'actioncolumn',
                text: 'Thao tác',
                align: 'center',
                width: 60,
                items: [{
                    icon: '../Content/icon/delete.gif',
                    tooltip: 'Xóa',
                    handler: function (grid, rowIndex, colIndex, item, e, record) {

                        Ext.Msg.show({
                            title: 'Xác nhận',
                            msg: 'Xác nhận xóa dữ liệu ?',
                            width: 250,
                            buttons: Ext.MessageBox.OKCANCEL,
                            buttonText: {
                                ok: 'Xóa',
                                cancel: 'Hủy'
                            },
                            icon: Ext.MessageBox.QUESTION,
                            fn: function (buttonId, text, opt) {
                                if (buttonId == 'ok') {
                                    var gridStore = grid.getStore();
                                    var rec = gridStore.getAt(rowIndex);
                                    if (rec) {
                                        var entity = {
                                            EmployeeId: rec.get('EmployeeId')
                                        };
                                        
                                        Ext.Ajax.request({
                                            url: '/api/ApiEmployee/Delete',
                                            method: 'POST',
                                            jsonData: entity,
                                            success: function (transport, option) {
                                                var responseData = Ext.decode(transport.responseText);
                                                if (responseData.success == true) {
                                                    gridStore.remove(rec);
                                                    
                                                } else {
                                                    Ext.MessageBox.show({
                                                        title: 'Lỗi',
                                                        msg: responseData.message,
                                                        icon: Ext.MessageBox.ERROR,
                                                        buttons: Ext.Msg.OK
                                                    });
                                                }
                                            },
                                            failure: function (transport, option) {
                                                var responseData = Ext.decode(transport.responseText);
                                                Ext.MessageBox.show({
                                                    title: 'Lỗi',
                                                    msg: responseData.message,
                                                    icon: Ext.MessageBox.ERROR,
                                                    buttons: Ext.Msg.OK
                                                });
                                            }
                                        });
                                    }
                                }
                                else if (buttonId == 'cancel') {

                                }
                            }
                        });
                    }
                }]
            }],
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    text: 'Thêm mới',
                    iconCls: 'icon-add',
                    handler: function () {
                        Ext.create('EmployeeWindow', {
                            id: 'newEmployeeWindow'
                        }).show();
                    }
                }]
            }],
            bbar: new Ext.PagingToolbar({
                pageSize: 15,
                store: employeeStore,
                displayInfo: true,
                displayMsg: 'Danh sách: {0} đến {1}.  Tổng số: {2}',
                emptyMsg: "Không có nhân viên nào"
            })
        });
        
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [employeeGrid]
        });
        
        Ext.define('EmployeeWindow', {
            extend: 'Ext.window.Window',
            title: 'Thông tin nhân viên',
            modal: true,
            header: {
                titleAlign: 'center'
            },
            closeable: true,
            resizable: {
                handles: 'e w'
            },
            width: 500,
            height: 400,
            minWidth: 400,
            layout: 'fit',
            items: {
                xtype: 'form',
                layout: 'form',
                bodyPadding: '10 10 5 10',
                fieldDefaults: {
                    msgTarget: 'side',
                    labelWidth: 100,
                    labelAlign: 'top'
                },
                plugins: {
                    ptype: 'datatip'
                },
                defaults: {
                    anchor: '100%'
                },
                items: [{
                    xtype: 'container',
                    layout: 'hbox',
                    items: [{
                        xtype: 'container',
                        flex: 1,
                        border: false,
                        layout: 'anchor',
                        defaultType: 'textfield',
                        items: [{
                            fieldLabel: 'Họ đệm',
                            afterLabelTextTpl: required,
                            id: 'txtFirstName',
                            anchor: '95%',
                            tooltip: 'Nhập họ đệm',
                            tabIndex: 1
                        }, {
                            fieldLabel: 'Ngày sinh',
                            xtype: 'datefield',
                            id: 'txtBirthDate',
                            anchor: '95%',
                            tooltip: 'Nhập ngày sinh',
                            tabIndex: 3
                        }, {
                            fieldLabel: 'Email',
                            id: 'txtEmail',
                            anchor: '95%',
                            tooltip: 'Nhập địa chỉ email',
                            tabIndex: 5
                        }]
                    }, {
                        xtype: 'container',
                        flex: 1,
                        border: false,
                        layout: 'anchor',
                        defaultType: 'textfield',
                        items: [{
                            fieldLabel: 'Tên',
                            afterLabelTextTpl: required,
                            id: 'txtLastName',
                            anchor: '100%',
                            tooltip: 'Nhập tên',
                            tabIndex: 2
                        }, {
                            fieldLabel: 'Số điện thoại',
                            id: 'txtMobilePhone',
                            anchor: '100%',
                            tooltip: 'Nhập điện thoại',
                            tabIndex: 4
                        }, {
                            fieldLabel: 'Địa chỉ',
                            id: 'txtAddress',
                            anchor: '100%',
                            tooltip: 'Nhập địa chỉ',
                            tabIndex: 6
                        }]
                    }]
                }, {
                    xtype: 'textareafield',
                    id: 'txtNote',
                    fieldLabel: 'Ghi chú',
                    height: 150,
                    grow: false,
                    tooltip: 'Nhập ghi chú',
                    tabIndex: 7
                }]
            },
            buttons: [{
                text: 'Lưu',
                id: 'btnSave',
                handler: function () {
                    var entity = {
                        FirstName: Ext.getCmp('txtFirstName').getValue(),
                        LastName: Ext.getCmp('txtLastName').getValue(),
                        BirthDate: Ext.getCmp('txtBirthDate').getValue(),
                        Address: Ext.getCmp('txtAddress').getValue().trim() != "" ? Ext.getCmp('txtAddress').getValue().trim() : null,
                        MobilePhone: Ext.getCmp('txtMobilePhone').getValue().trim() != "" ? Ext.getCmp('txtMobilePhone').getValue().trim() : null,
                        Email: Ext.getCmp('txtEmail').getValue().trim() != "" ? Ext.getCmp('txtEmail').getValue().trim() : null,
                        Note: Ext.getCmp('txtNote').getValue().trim() != "" ? Ext.getCmp('txtNote').getValue().trim() : null
                    };

                    Ext.Ajax.request({
                        url: '/api/ApiEmployee/Create',
                        method: 'POST',
                        jsonData: entity,
                        success: function (transport, option) {
                            var responseData = Ext.decode(transport.responseText);
                            if (responseData.success == true) {
                                //alert("Success. " + responseData.message);

                                employeeGrid.getStore().insert(0, responseData.data);
                            } else {
                                Ext.MessageBox.show({
                                    title: 'Lỗi',
                                    msg: responseData.message,
                                    icon: Ext.MessageBox.ERROR,
                                    buttons: Ext.Msg.OK
                                });
                            }
                        },
                        failure: function (transport, option) {
                            var responseData = Ext.decode(transport.responseText);
                            Ext.MessageBox.show({
                                title: 'Lỗi',
                                msg: responseData.message,
                                icon: Ext.MessageBox.ERROR,
                                buttons: Ext.Msg.OK
                            });
                        }
                    });
                },
                tabIndex: 8
            }, {
                text: 'Hủy',
                handler: function () {
                    Ext.getCmp('newEmployeeWindow').close();
                },
                tabIndex: 9
            }],
            listeners: {
                afterrender: function (win, eOpts) {
                    var txt = Ext.getCmp('txtFirstName');
                    if (txt) {
                        txt.focus(false, 100);
                    }
                }
            }
        });
    });

</script>
